package com.nova.bluetooth.ui.ai.aiNote;


import static com.nova.bluetooth.xunFeiSDK.engine.EngineConstants.RECORDER_DATA;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.nova.bluetooth.R;
import com.nova.bluetooth.base.CommonMessageWrap;
import com.nova.bluetooth.databinding.ActivityVoiceFileToTextBinding;
import com.nova.bluetooth.helpUtils.EventBusUtil;
import com.nova.bluetooth.helpUtils.FileUtil;
import com.nova.bluetooth.helpUtils.LogUtil;
import com.nova.bluetooth.helpUtils.OnClickEvent;
import com.nova.bluetooth.helpUtils.ToastUtils;
import com.nova.bluetooth.permission.OnPermissionListener;
import com.nova.bluetooth.permission.PermissionManageActivity;
import com.nova.bluetooth.permission.PermissionType;
import com.nova.bluetooth.rtasrWSS.XunFeiRTASRManager;
import com.nova.bluetooth.widget.CommonDialog;
import com.nova.bluetooth.xunFeiSDK.engine.EngineConstants;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class AudioFileToTextActivity extends PermissionManageActivity implements
        XunFeiRTASRManager.OnRTASRResultListener {
    private XunFeiRTASRManager mRtasrManager;
    private ActivityVoiceFileToTextBinding binding;
    private AudioFileViewModel audioFileViewModel;


    private ProgressDialog progressDialog;


    private void showProgressDialog() {
        // 显示 ProgressDialog
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    private void dismissProgressDialog() {
        // 隐藏 ProgressDialog
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        EdgeToEdge.enable(this);
        initBinding();
        setContentView(binding.getRoot());
        initView();
        initData();
        observe();

        mRtasrManager = XunFeiRTASRManager.getInstance();
        XunFeiRTASRManager.isTranslate = false;
        mRtasrManager.setOnRTASRResultListener(this);
        setRTASRConfig();
    }



    private void observe() {
        audioFileViewModel.mFFmpegAudioFilePath.observe(this, file -> {
            if (file != null && !file.isEmpty()){
                LogUtil.d("test==>转换成功后的文件:" + file);
                startRTASRWithFile(file);
            }
        });
        audioFileViewModel.showProgressDialog.observe(this, result -> {
            if (result.first) {
                showProgressDialog();
            } else {
                dismissProgressDialog();
            }
        });
    }

    private void initBinding() {
        binding = ActivityVoiceFileToTextBinding.inflate(getLayoutInflater());
        audioFileViewModel = new ViewModelProvider(this).get(AudioFileViewModel.class);
        binding.setOnClick(new MyOnClickEvent());
    }

    private void initView() {
        EngineConstants.saveAudio = true;
        EventBusUtil.register(this);
        // 初始化 ProgressDialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在导入音频...");
        progressDialog.setCancelable(false);
        binding.tvTitle.setText("导入音频转写");
    }


    @SuppressLint("MissingPermission")
    @Override
    public void onDestroy() {
        EngineConstants.saveAudio = false;
        EventBusUtil.unRegister(this);
        super.onDestroy();
        mRtasrManager.clearData();
        mRtasrManager.onDestroy();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 202 && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                String path = uri.toString();
                String realPathFromUri = FileUtil.getPath(this, Uri.parse(path));
                checkFileToDealwith(realPathFromUri);
            }
        }
    }

    private void checkFileToDealwith(String filePath) {
        if (filePath.endsWith(".wav") || filePath.endsWith(".mp3") || filePath.endsWith(".m4a")) {
            LogUtil.d("文件格式正确");
        } else {
            ToastUtils.show("文件格式错误");
            return;
        }


        File file = new File(filePath);
        if (!file.exists()) {
            ToastUtils.show("文件已存在");
            return;
        }
        int length = FileUtil.getFileSizeKB(file);
        LogUtil.d(TAG+"文件大小= " + length);
        audioFileViewModel.dealwithAudioFile(file);
    }

    private void initData() {
    }

    /****************************RTASR start******************************/
    private void startRTASRWithFile(String filePath) {
        XunFeiRTASRManager.getInstance().startWebSocketClientWithFile(filePath);
    }
    @Override
    public void onRTASRResult(String result, StringBuffer bufferResult) {

    }

    @Override
    public void onRTASRTranslateResult(String result, StringBuffer bufferResult) {

    }

    @Override
    public void onRTASROffline() {
        binding.getRoot().post(() -> {
            if (!binding.etContent.getText().toString().isEmpty()){
                binding.btnAudioOutput.setVisibility(View.VISIBLE);
                binding.btnAudioInput.setVisibility(View.GONE);
            }
        });
    }

    private StringBuffer type_0_data = new StringBuffer();

    @Override
    public void onRTASRShortResult(String result, int type) {
        if (type == 0) {
            type_0_data.append(result);
            result = "";
        }

        String finalResult = result;
        binding.getRoot().post(() -> {
           binding.etContent.setText(type_0_data.toString() + finalResult);
           binding.etContent.scrollToBottom();
        });
    }

    @Override
    public void onRTASRTranslateShortResult(String result, int type) {

    }
    /****************************RTASR end******************************/

    /********************************语言选择start*********************************/

    private String asrLanguage = "cn";
    private int asrLanguageType = 1;
    private String translateLanguage = "en";
    private boolean isTranslate = false;
    private boolean translateLanguageUnable = true;  //翻译语言是否可用

    /**
     * 更新实时语音转写参数，参数改变都应该调用该方法更新下
     */
    private void setRTASRConfig() {
        XunFeiRTASRManager.isTranslate = isTranslate;
        XunFeiRTASRManager.RTASR_LANG = asrLanguage;
        XunFeiRTASRManager.RTASR_TRANSLATE_LANG = translateLanguage;
    }

    /********************************语言选择end*********************************/

    /**
     * 外部文件读取权限
     */
    private void requestStoragePermission() {
        getManageExternalStoragePermission(new OnPermissionListener() {
            @Override
            public void onPermissionGranted(PermissionType permissionType) {
                goImportAudio();
            }

            @Override
            public void onPermissionDenied(PermissionType permissionType) {

            }
        },"获取文件读取权限用于导入音频进行语音识别");
    }

    /**
     * 导入音频
     */
    private void goImportAudio() {
        final Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.setType("audio/*");
        startActivityForResult(intent, 202);
    }


    private void doBtnSave() {
        getReadMediaPermission(new com.nova.bluetooth.permission.OnPermissionListener() {
            @Override
            public void onPermissionGranted(PermissionType permissionType) {
                showOutputLogDialog();
            }

            @Override
            public void onPermissionDenied(PermissionType permissionType) {
                ToastUtils.show("未获得文件读写权限，无法操作下一步");
            }
        }, "");
    }

    private void showOutputLogDialog() {
        CommonDialog dialog = new CommonDialog(this, R.layout.dialog_output_log);
        dialog.setWidth(R.dimen.dp_320);
        dialog.setCancelable(true);
        dialog.setGravity(Gravity.CENTER);
        dialog.showDialog();

        TextView title = dialog.getDialog().findViewById(R.id.tv_title);
        title.setText("导出识别结果");
        TextView tips  = dialog.getDialog().findViewById(R.id.tv_tips);
        dialog.getDialog().findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismissDialog();
            }
        });
        dialog.getDialog().findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveContentToFile(binding.etContent.getText().toString());
                dialog.dismissDialog();
            }
        });
    }

    public void saveContentToFile(String content) {
        new Thread(() -> {
            String fileName = "语音识别结果_" + System.currentTimeMillis() + ".txt";
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), fileName);

            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(content.getBytes());
                Log.d("PermissionActivity", "saveContentToFile: " + file.getAbsolutePath());
                runOnUiThread(() -> ToastUtils.show("已保存到: " + file.getAbsolutePath()));
            } catch (IOException e) {
                runOnUiThread(() -> ToastUtils.show("保存失败: " + e.getMessage()));
            }
        }).start();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(CommonMessageWrap message) {
        switch (message.getEventCode()) {
            case RECORDER_DATA:
                byte[] audioData = (byte[]) message.getObject();
                //可用于根据声音大小制作振幅动效图
                break;
        }
    }


    public class MyOnClickEvent extends OnClickEvent {

        @Override
        public void singleClick(View v) {
            int id = v.getId();
            if (id == R.id.iv_back) {
                finish();
            } else if (id == R.id.btn_audio_input) {
                requestStoragePermission();
            }else if (id == R.id.btn_audio_output){
                doBtnSave();
            }
        }
    }
}
